// 缓存用户
const users = [];
// 保存聊天记录
const message = [];
// 创建随机颜色
const createBgColor = () => {
  return "#" + parseInt(Math.random() * 0xffffff).toString(16);
};

module.exports = (io, socket) => {
  io.emit("messageInfo", { users, message });
  socket.on("joinRoom", (name) => {
    let userIndex = users.findIndex((user) => user.name === name);
    if (userIndex === -1) {
      let user = {
        name,
        bgColor: createBgColor(),
        joinTime: new Date().getTime(),
      };
      users.push(user);
      socket.emit("join-user", user);
      io.emit("alreadyJoinedRoom", { name: user.name, users });
      console.log(users);
    } else {
      socket.emit("joinRoom", "该用户已存在");
    }
  });

  socket.on("sendMessage", (data) => {
    message.push(data);
    console.log(data);
    io.emit("sendMessage", data);
  });
};
